<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="登录账号"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getUsers">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="users" highlight-current-row v-loading="listLoading"
                  height="650" :row-class-name="tableRowClassName" @selection-change="selChange">
            <el-table-column type="selection" width="90">
            </el-table-column>
            <el-table-column type="index" width="70">
            </el-table-column>
            <el-table-column prop="loginName" label="登录账号" width="210" sortable>
            </el-table-column>
            <el-table-column prop="password" label="登录密码" width="210" sortable>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="210" sortable>
            </el-table-column>
            <el-table-column prop="isUse" label="是否使用" min-width="210" :formatter="formatIsUse" sortable>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.selectList.length===0">批量删除</el-button>
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-sizes="[20, 50, 100, 500, 1000]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
                <el-form-item label="登录账号" prop="loginName">
                    <el-input v-model="editForm.loginName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password">
                    <el-input v-model="editForm.password"></el-input>
                </el-form-item>
                <el-form-item label="用户头像" prop="avatar">
                    <el-upload
                            class="avatar-uploader"
                            action="/api/codeing/sysUser/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="avatar" :src="avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker type="date" placeholder="选择日期" v-model="editForm.createTime"></el-date-picker>
                </el-form-item>
                <el-form-item label="角色">
                    <div class="check-group">
                        <!-- 纵向展示角色多选
                        <el-checkbox-group v-model="userRoleId" :min="1">
                            <div v-for="data in roles" style="width: 170px;">
                                <el-checkbox :label="data.id" :key="data.name" @change="handleChange">
                                    {{data.name}}
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>-->
                        <el-checkbox-group v-model="userRoleId" :min="1">
                            <el-checkbox v-for="data in roles" :label="data.id" :key="data.name" @change="handleChange">
                                {{data.name}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item label="是否使用" prop="isUse">
                    <el-radio-group v-model="editForm.isUse">
                        <el-radio class="radio" label="Y">是</el-radio>
                        <el-radio class="radio" label="N">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="editFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

        <!--新增界面-->
        <el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="登录账号" prop="loginName">
                    <el-input v-model="addForm.loginName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="用户头像" prop="avatar">
                    <el-upload
                            class="avatar-uploader"
                            action="/api/codeing/sysUser/upload"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="avatar" :src="avatar" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker type="date" placeholder="选择日期" v-model="addForm.createTime"></el-date-picker>
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <div class="check-group">
                        <!-- 纵向展示角色多选
                        <el-checkbox-group v-model="userRoleId" :min="1">
                            <div v-for="data in roles" style="width: 170px;">
                                <el-checkbox :label="data.id" :key="data.name" @change="handleChange">
                                    {{data.name}}
                                </el-checkbox>
                            </div>
                        </el-checkbox-group>-->
                        <el-checkbox-group v-model="addForm.role">
                            <el-checkbox v-for="data in roles" :label="data.id" :key="data.name" @change="handleChange">
                                {{data.name}}
                            </el-checkbox>
                        </el-checkbox-group>
                    </div>
                </el-form-item>
                <el-form-item label="是否使用" prop="isUse">
                    <el-radio-group v-model="addForm.isUse">
                        <el-radio class="radio" label="Y">是</el-radio>
                        <el-radio class="radio" label="N">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    import {
        getUserListPage,
        removeUser,
        batchRemoveUser,
        editUser,
        addUser,
        getRolesByUserId,
        getAllRoles
    } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    name: ''
                },
                users: [],
                userRoleId: [], // 具有的角色id
                avatar: '', // 用户头像地址
                total: 0,
                pageSize: 20,
                page: 1,
                listLoading: false,
                selectList: [],//列表选中列
                roles: [], // 所有角色
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    loginName: [
                        {required: true, message: '请输入登录账号', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入登录密码', trigger: 'blur'}
                    ]
                },
                //编辑界面数据
                editForm: {
                    loginName: '',
                    password: '',
                    createTime: '',
                    isUse: ''
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    loginName: [
                        {required: true, message: '请输入登录账号', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入登录密码', trigger: 'blur'}
                    ],
                    isUse: [
                        {required: true, message: '请选择是否使用', trigger: 'change'}
                    ],
                    createTime: [
                        {type: 'date', required: true, message: '请输入创建日期', trigger: 'change'}
                    ],
                    role: [
                        {type: 'array', required: true, message: '请选择角色', trigger: 'change'}
                    ]
                },
                //新增界面数据
                addForm: {
                    loginName: '',
                    password: '',
                    createTime: '',
                    isUse: ''
                }

            }
        },
        methods: {
            handleAvatarSuccess(res, file) {
                // 拿到后台返回的图片链接地址
                this.avatar = res.data;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            handleChange() {
                // console.log(this.userRoleId);
            },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.getUsers();
            },
            //获取用户列表
            getUsers() {
                let para = {
                    pageSize: this.pageSize,
                    currentPage: this.page,
                    whereMap:
                        {
                            loginName: this.filters.name
                        }
                };
                this.listLoading = true;
                getUserListPage(para).then((res) => {
                    this.total = res.data.data.totalRecord;
                    this.users = res.data.data.resultObject;
                    this.listLoading = false;
                });
            },
            getRoles() {
                getAllRoles().then((res) => {
                    this.roles = res.data.data;
                });
            },
            // 删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = row.id;
                    removeUser(para).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
                this.avatar = row.avatar;
                let para = row.id;
                getRolesByUserId(para).then((res) => {
                    this.userRoleId = res.data.data.userRoleId;
                });
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.avatar = '';
                this.userRoleId = [];
                this.addForm = {
                    loginName: '',
                    password: '',
                    createTime: '',
                    isUse: '',
                    role: []
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            para.createTime = (!para.createTime || para.createTime == '') ? '' : util.formatDate.format(new Date(para.createTime), 'yyyy-MM-dd');
                            para.roleList = this.userRoleId;
                            para.avatar = this.avatar;
                            editUser(para).then((res) => {
                                this.editLoading = false;
                                // === 用于（严格）比较、判断两者（严格）相等，不会进行自动转换，要求进行比较的操作数必须类型一致，不一致时返回false
                                if (res.data.code === 200) {
                                    this.$message({
                                        message: res.data.msg,
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                } else {
                                    this.$message({
                                        message: res.data.msg,
                                        type: 'error'
                                    });
                                }
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            let para = Object.assign({}, this.addForm);
                            para.createTime = (!para.createTime || para.createTime == '') ? '' : util.formatDate.format(new Date(para.createTime), 'yyyy-MM-dd');
                            para.avatar = this.avatar;
                            addUser(para).then((res) => {
                                this.addLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.getUsers();
                            });
                        });
                    }
                });
            },
            selChange: function (selects) {
                this.selectList = selects;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.selectList.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = {ids: ids};
                    batchRemoveUser(para).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });
                }).catch(() => {

                });
            },
            tableRowClassName(row, rowIndex) {
                if (row.isUse == 'N') {
                    return 'warning-row';
                } else if (row.isUse == 'Y') {
                    return '';
                }
                return '';
            },
            formatIsUse(row, column) {
                if (row.isUse == 'N') {
                    return '禁用';
                } else if (row.isUse == 'Y') {
                    return '可使用';
                }
                return '';
            }
        },
        mounted() {
            this.getUsers();
            this.getRoles();
        }
    }

</script>

<style>
    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }

    .el-checkbox + .el-checkbox {
        margin-left: 0px;
    }

    .el-checkbox {
        margin-right: 25px;
    }

    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>